from django.db import transaction
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.db.models import Q, Count
from django.utils import timezone
from django.conf import settings
from math import radians, cos, sin, asin, sqrt

# activities/views.py - 在导入部分添加
from .models import Activity, ActivityCategory, ActivityRegistration, ActivityComment, ActivityRating, ActivityImage, CommentImage
from social.models import CommentLike
from points.utils import award_points
from social.models import CommentLike, Follow
from django.db.models.functions import Greatest


def can_like_comment(user):
    """检查用户是否可以点赞评论 - 所有登录用户都可以"""
    return user.is_authenticated




# 在 activities/views.py 中添加
@login_required
def simple_comment_like(request, comment_id):
    """修复后的点赞评论功能"""
    try:
        comment = get_object_or_404(ActivityComment, id=comment_id)

        with transaction.atomic():
            # 使用 select_for_update 锁定记录防止竞态条件
            locked_comment = ActivityComment.objects.select_for_update().get(id=comment_id)

            # 检查点赞状态
            like_exists = CommentLike.objects.filter(
                user=request.user,
                comment=locked_comment
            ).exists()

            if like_exists:
                # 取消点赞
                deleted_count = CommentLike.objects.filter(
                    user=request.user,
                    comment=locked_comment
                ).delete()[0]

                if deleted_count > 0:
                    # 确保点赞数不会变成负数
                    new_count = max(locked_comment.likes_count - 1, 0)
                    locked_comment.likes_count = new_count
                    locked_comment.save()
                action = 'unliked'
                current_count = max(locked_comment.likes_count, 0)
            else:
                # 点赞
                CommentLike.objects.create(
                    user=request.user,
                    comment=locked_comment
                )
                locked_comment.likes_count = locked_comment.likes_count + 1
                locked_comment.save()
                action = 'liked'
                current_count = locked_comment.likes_count

            # 重新从数据库获取最新状态
            comment.refresh_from_db()

            return JsonResponse({
                'success': True,
                'action': action,
                'likes_count': comment.likes_count,
                'comment_id': comment_id
            })

    except Exception as e:
        print(f"点赞操作错误: {str(e)}")
        return JsonResponse({
            'success': False,
            'message': f'操作失败: {str(e)}'
        })



def activity_list(request):
    """活动列表"""
    # 这里应该显示所有已批准的活动，而不仅仅是当前用户的活动
    activities = Activity.objects.filter(status='approved').select_related('creator', 'category')

    # 搜索
    search = request.GET.get('search', '')
    if search:
        activities = activities.filter(
            Q(title__icontains=search) | Q(description__icontains=search)
        )

    # 分类筛选
    category_id = request.GET.get('category')
    if category_id:
        activities = activities.filter(category_id=category_id)

    # 排序
    sort_by = request.GET.get('sort', '-created_at')
    if sort_by == 'popular':
        activities = activities.annotate(reg_count=Count('registrations')).order_by('-reg_count')
    elif sort_by == 'upcoming':
        activities = activities.filter(start_time__gte=timezone.now()).order_by('start_time')
    else:
        activities = activities.order_by(sort_by)

    # 添加分页
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    page = request.GET.get('page', 1)
    paginator = Paginator(activities, 6)  # 每页显示9个活动

    try:
        activities_page = paginator.page(page)
    except PageNotAnInteger:
        activities_page = paginator.page(1)
    except EmptyPage:
        activities_page = paginator.page(paginator.num_pages)

    categories = ActivityCategory.objects.all()

    context = {
        'activities': activities_page,  # 使用分页后的数据
        'categories': categories,
        'search': search,
        'current_category': category_id,
        'sort_by': sort_by,
        'paginator': paginator,
        'page_obj': activities_page,

    }
    return render(request, 'activities/activity_list.html', context)


def activity_detail(request, activity_id):
    """活动详情"""
    try:
        activity = get_object_or_404(
            Activity.objects.select_related('creator', 'category'),
            id=activity_id
        )

        # 计算活动时间状态
        now = timezone.now()
        time_until_start = activity.start_time - now if activity.start_time > now else None

        # 增加浏览次数
        activity.view_count += 1
        activity.save(update_fields=['view_count'])

        # 获取评论
        comments = activity.comments.filter(parent=None).select_related('user').prefetch_related(
            'replies',
            'replies__user',
            'images',  # 预加载评论图片
            'replies__images'  # 预加载回复图片
        )

        # 获取评分 - 在函数顶部定义，确保始终有值
        user_rating = None
        if request.user.is_authenticated:
            try:
                user_rating = ActivityRating.objects.get(activity=activity, user=request.user)
            except ActivityRating.DoesNotExist:
                user_rating = None

            # 为每个评论添加用户点赞状态
            for comment in comments:
                comment.user_has_liked = CommentLike.objects.filter(
                    user=request.user,
                    comment=comment
                ).exists()

                for reply in comment.replies.all():
                    reply.user_has_liked = CommentLike.objects.filter(
                        user=request.user,
                        comment=reply
                    ).exists()

        # 检查用户是否已报名和签到状态
        is_registered = False
        is_checked_in = False
        registration = None

        if request.user.is_authenticated:
            try:
                registration = ActivityRegistration.objects.get(
                    activity=activity,
                    user=request.user,
                    status='registered'
                )
                is_registered = True
                is_checked_in = registration.is_checked_in
            except ActivityRegistration.DoesNotExist:
                pass

        # 是否为活动创建者
        is_creator = request.user.is_authenticated and activity.creator == request.user

        # 检查当前用户是否已关注活动发起者
        is_following = False
        if request.user.is_authenticated and request.user != activity.creator:
            is_following = Follow.objects.filter(
                follower=request.user,
                following=activity.creator
            ).exists()

        # 获取相关活动 - 相同分类的其他已批准活动，排除当前活动
        related_activities = Activity.objects.filter(
            category=activity.category,
            status='approved'
        ).exclude(id=activity.id).select_related('creator', 'category')[:4]  # 限制显示4个

        # 构建完整的上下文
        context = {
            'activity': activity,
            'comments': comments,
            'user_rating': user_rating,  # 确保这个变量总是被定义
            'is_registered': is_registered,
            'is_checked_in': is_checked_in,
            'registration': registration,
            'is_creator': is_creator,
            'average_rating': activity.get_average_rating(),
            'is_following': is_following,
            'related_activities': related_activities,
            'user': request.user,  # 确保传递用户对象
            'can_rate': activity.can_user_rate(request.user) if request.user.is_authenticated else False,
            'time_until_start': time_until_start,  # 新增
            'now': now,  # 新增，用于模板中比较时间
        }

        # 如果是部分刷新请求，只返回评论部分的HTML
        if request.GET.get('partial') == 'comments':
            # 部分刷新时也需要完整的评论上下文
            return render(request, 'activities/partials/comments_list.html', context)

        return render(request, 'activities/activity_detail.html', context)

    except Exception as e:
        # 记录错误日志
        print(f"活动详情页错误: {str(e)}")
        import traceback
        traceback.print_exc()

        # 返回错误页面或重定向到活动列表
        messages.error(request, '加载活动详情时出现错误')
        return redirect('activities:activity_list')


@login_required
def activity_create(request):
    """创建活动"""
    if request.method == 'POST':
        title = request.POST.get('title')
        description = request.POST.get('description')
        category_id = request.POST.get('category')
        start_time = request.POST.get('start_time')
        end_time = request.POST.get('end_time')
        location = request.POST.get('location')
        latitude = request.POST.get('latitude')
        longitude = request.POST.get('longitude')
        max_participants = request.POST.get('max_participants')
        
        activity = Activity.objects.create(
            title=title,
            description=description,
            category_id=category_id,
            creator=request.user,
            start_time=start_time,
            end_time=end_time,
            location=location,
            latitude=latitude if latitude else None,
            longitude=longitude if longitude else None,
            max_participants=max_participants,
            status='pending'  # 待审核
        )
        
        if 'cover_image' in request.FILES:
            activity.cover_image = request.FILES['cover_image']
            activity.save()
        
        # 奖励积分
        award_points(request.user, 'activity_create', f'创建活动：{activity.title}')
        
        messages.success(request, '活动创建成功，等待管理员审核')
        return redirect('activities:activity_detail', activity_id=activity.id)
    
    categories = ActivityCategory.objects.all()
    context = {
        'categories': categories,
        'amap_api_key': settings.AMAP_API_KEY,
    }
    return render(request, 'activities/activity_create.html', context)


@login_required
def activity_edit(request, activity_id):
    """编辑活动"""
    activity = get_object_or_404(Activity, id=activity_id)

    # 只有创建者和管理员可以编辑
    if activity.creator != request.user and not request.user.is_admin_user():
        messages.error(request, '您没有权限编辑此活动')
        return redirect('activities:activity_detail', activity_id=activity_id)

    if request.method == 'POST':
        activity.title = request.POST.get('title')
        activity.description = request.POST.get('description')
        activity.category_id = request.POST.get('category')
        activity.start_time = request.POST.get('start_time')
        activity.end_time = request.POST.get('end_time')
        activity.location = request.POST.get('location')
        activity.latitude = request.POST.get('latitude') or None
        activity.longitude = request.POST.get('longitude') or None
        activity.max_participants = request.POST.get('max_participants')

        # 关键修改：将状态重置为待审核
        activity.status = 'pending'

        # 处理封面图片
        if 'cover_image' in request.FILES:
            activity.cover_image = request.FILES['cover_image']

        # 处理移除封面图片的选项
        if request.POST.get('remove_cover_image'):
            activity.cover_image.delete(save=False)  # 删除文件
            activity.cover_image = None

        activity.save()
        messages.success(request, '活动更新成功，已重新提交审核，等待管理员审核')
        return redirect('activities:activity_detail', activity_id=activity_id)

    categories = ActivityCategory.objects.all()
    context = {
        'activity': activity,
        'categories': categories,
        "amap_api_key": settings.AMAP_API_KEY,
    }
    return render(request, 'activities/activity_edit.html', context)


@login_required
def activity_delete(request, activity_id):
    """删除活动"""
    activity = get_object_or_404(Activity, id=activity_id)
    
    # 只有创建者和管理员可以删除
    if activity.creator != request.user and not request.user.is_admin_user():
        messages.error(request, '您没有权限删除此活动')
        return redirect('activities:activity_detail', activity_id=activity_id)
    
    if request.method == 'POST':
        activity.delete()
        messages.success(request, '活动已删除')
        return redirect('activities:activity_list')
    
    return render(request, 'activities/activity_delete_confirm.html', {'activity': activity})


@login_required
def activity_register(request, activity_id):
    """报名活动"""
    activity = get_object_or_404(Activity, id=activity_id)

    if not activity.can_register():
        return JsonResponse({'success': False, 'message': '活动无法报名'})

    # 检查是否已报名（包括任何状态）
    existing_registration = ActivityRegistration.objects.filter(
        activity=activity,
        user=request.user
    ).first()

    if existing_registration:
        if existing_registration.status == 'registered':
            return JsonResponse({'success': False, 'message': '您已报名此活动'})
        else:
            # 如果是取消状态，重新激活
            existing_registration.status = 'registered'
            existing_registration.is_checked_in = False
            existing_registration.checked_in_at = None
            existing_registration.save()
    else:
        # 创建新的报名记录
        ActivityRegistration.objects.create(
            activity=activity,
            user=request.user,
            status='registered'
        )

    # 更新参与人数
    activity.current_participants = ActivityRegistration.objects.filter(
        activity=activity,
        status='registered'
    ).count()
    activity.save()

    # 奖励积分
    award_points(request.user, 'activity_join', f'参加活动：{activity.title}')

    return JsonResponse({'success': True, 'message': '报名成功'})


@login_required
def activity_unregister(request, activity_id):
    """取消报名 - 活动开始前可以取消，并扣除报名积分"""
    activity = get_object_or_404(Activity, id=activity_id)

    try:
        registration = ActivityRegistration.objects.get(
            activity=activity,
            user=request.user,
            status='registered'
        )
    except ActivityRegistration.DoesNotExist:
        return JsonResponse({'success': False, 'message': '您未报名此活动'})

    # 检查活动是否已开始 - 活动开始后不能取消报名
    from django.utils import timezone
    if timezone.now() >= activity.start_time:
        return JsonResponse({'success': False, 'message': '活动已开始，无法取消报名'})

    # 取消报名
    registration.status = 'cancelled'
    registration.save()

    # 更新参与人数
    activity.current_participants = ActivityRegistration.objects.filter(
        activity=activity,
        status='registered'
    ).count()
    activity.save()

    # 扣除报名时获得的积分
    try:
        from points.models import UserPoints, PointsRecord

        # 查找报名时获得的积分记录
        join_record = PointsRecord.objects.filter(
            user=request.user,
            type='activity_join',
            description__contains=f'参加活动：{activity.title}'
        ).first()

        if join_record:
            # 获取用户积分
            user_points, created = UserPoints.objects.get_or_create(user=request.user)

            # 计算要扣除的积分（报名获得的积分）
            deduction_amount = abs(join_record.points)  # 取绝对值确保是正数

            # 确保积分不会变成负数
            if user_points.available_points >= deduction_amount:
                # 更新用户积分
                user_points.total_points -= deduction_amount
                user_points.available_points -= deduction_amount
                user_points.save()

                # 创建扣除积分的记录
                PointsRecord.objects.create(
                    user=request.user,
                    points=-deduction_amount,  # 负数表示扣除
                    type='activity_join_cancel',
                    description=f'取消报名活动：{activity.title}'
                )

                print(f"成功扣除 {deduction_amount} 积分")
            else:
                # 如果积分不足，只扣除可用积分
                actual_deduction = user_points.available_points
                user_points.total_points -= actual_deduction
                user_points.available_points = 0
                user_points.save()

                PointsRecord.objects.create(
                    user=request.user,
                    points=-actual_deduction,
                    type='activity_join_cancel',
                    description=f'取消报名活动：{activity.title}（部分扣除，原应扣除{deduction_amount}）'
                )

                print(f"积分不足，只扣除了 {actual_deduction} 积分")
        else:
            print("未找到报名积分记录，无法扣除积分")

    except Exception as e:
        print(f"扣除积分失败: {e}")
        import traceback
        traceback.print_exc()

    return JsonResponse({'success': True, 'message': '已取消报名'})


@login_required
def activity_checkin(request, activity_id):
    """活动签到 - 只有活动开始后才能签到"""
    activity = get_object_or_404(Activity, id=activity_id)

    # 检查活动是否已经开始
    if not activity.can_check_in():
        return JsonResponse({'success': False, 'message': '活动尚未开始，无法签到'})

    try:
        registration = ActivityRegistration.objects.get(
            activity=activity,
            user=request.user,
            status='registered'
        )
    except ActivityRegistration.DoesNotExist:
        return JsonResponse({'success': False, 'message': '您未报名此活动'})

    if registration.is_checked_in:
        return JsonResponse({'success': False, 'message': '您已签到'})

    # 签到
    registration.is_checked_in = True
    registration.checked_in_at = timezone.now()
    registration.save()

    # 奖励积分
    award_points(request.user, 'activity_checkin', f'签到活动：{activity.title}')

    return JsonResponse({'success': True, 'message': '签到成功'})


@login_required
def activity_participants(request, activity_id):
    """活动参与者列表"""
    activity = get_object_or_404(Activity, id=activity_id)
    
    # 只有创建者和管理员可以查看
    if activity.creator != request.user and not request.user.is_admin_user():
        messages.error(request, '您没有权限查看参与者列表')
        return redirect('activities:activity_detail', activity_id=activity_id)
    
    registrations = ActivityRegistration.objects.filter(
        activity=activity,
        status='registered'
    ).select_related('user')
    
    context = {
        'activity': activity,
        'registrations': registrations,
    }
    return render(request, 'activities/activity_participants.html', context)


@login_required
def activity_comment(request, activity_id):
    """发表评论或回复 - 支持图片上传"""
    if request.method == 'POST':
        activity = get_object_or_404(Activity, id=activity_id)
        content = request.POST.get('content', '').strip()
        parent_id = request.POST.get('parent_id')
        uploaded_images = request.FILES.getlist('images')

        print(f"收到评论请求: 内容长度={len(content)}, 图片数量={len(uploaded_images)}")

        # 验证评论内容
        if not content and not uploaded_images:
            return JsonResponse({'success': False, 'message': '评论内容或图片不能为空'})

        # 创建评论
        comment = ActivityComment.objects.create(
            activity=activity,
            user=request.user,
            content=content,
            parent_id=parent_id if parent_id else None
        )

        print(f"评论创建成功, ID={comment.id}")

        # 保存图片
        image_urls = []
        for i, image_file in enumerate(uploaded_images):
            try:
                print(f"正在保存第 {i+1} 张图片: {image_file.name}")
                comment_image = CommentImage.objects.create(
                    comment=comment,
                    user=request.user,
                    image=image_file
                )
                image_data = {
                    'url': comment_image.get_image_url(),
                    'thumbnail': comment_image.get_thumbnail_url(),
                    'id': comment_image.id
                }
                image_urls.append(image_data)
                print(f"图片保存成功: {image_data}")
            except Exception as e:
                print(f"图片上传失败: {e}")
                continue

        # 奖励积分（只对顶级评论奖励，且每个活动每个用户只能获得一次）
        if not parent_id and (content or uploaded_images):
            award_points(request.user, 'comment', f'评论活动：{activity.title}', activity_id=activity.id)

        response_data = {
            'success': True,
            'comment': {
                'id': comment.id,
                'user': comment.user.nickname or comment.user.username,
                'user_id': comment.user.id,
                'avatar_url': comment.user.get_avatar_url(),
                'content': comment.content,
                'created_at': comment.created_at.strftime('%Y-%m-%d %H:%M'),
                'is_own_comment': True,
                'parent_id': parent_id,
                'images': image_urls
            }
        }
        print(f"返回响应: {response_data}")
        return JsonResponse(response_data)

    return JsonResponse({'success': False, 'message': '请求方法错误'})


# activities/views.py - 添加删除评论图片的视图

@login_required
def delete_comment_image(request, image_id):
    """删除评论图片"""
    if request.method == 'POST':
        try:
            comment_image = get_object_or_404(CommentImage, id=image_id)

            # 检查权限：只有图片上传者或评论作者可以删除
            if comment_image.user != request.user and comment_image.comment.user != request.user:
                return JsonResponse({'success': False, 'message': '没有权限删除此图片'})

            # 删除图片
            image_id = comment_image.id
            comment_image.delete()

            return JsonResponse({
                'success': True,
                'message': '图片已删除',
                'image_id': image_id
            })

        except Exception as e:
            return JsonResponse({'success': False, 'message': f'删除失败: {str(e)}'})

    return JsonResponse({'success': False, 'message': '请求方法错误'})


@login_required
def comment_delete(request, comment_id):
    """删除评论"""
    if request.method == 'POST':
        comment = get_object_or_404(ActivityComment, id=comment_id)

        # 检查权限：只有评论作者可以删除
        if comment.user != request.user:
            return JsonResponse({'success': False, 'message': '没有权限删除此评论'})


        # 删除评论
        comment_id = comment.id
        comment.delete()

        return JsonResponse({
            'success': True,
            'message': '评论已删除',
            'comment_id': comment_id
        })

    return JsonResponse({'success': False, 'message': '请求方法错误'})


@login_required
def activity_rate(request, activity_id):
    """评分活动 - 只有报名用户才能评分"""
    if request.method == 'POST':
        activity = get_object_or_404(Activity, id=activity_id)
        score = int(request.POST.get('score'))

        if score < 1 or score > 5:
            return JsonResponse({'success': False, 'message': '评分范围为1-5星'})

        # 检查用户是否已报名该活动
        is_registered = ActivityRegistration.objects.filter(
            activity=activity,
            user=request.user,
            status='registered'
        ).exists()

        if not is_registered:
            return JsonResponse({
                'success': False,
                'message': '只有报名参加活动的用户才能进行评分'
            })

        # 创建或更新评分
        rating, created = ActivityRating.objects.update_or_create(
            activity=activity,
            user=request.user,
            defaults={'score': score}
        )

        # 如果是新评分，奖励积分
        if created:
            award_points(request.user, 'rating', f'评分活动：{activity.title}')

        return JsonResponse({
            'success': True,
            'message': '评分成功',
            'average_rating': activity.get_average_rating()
        })

    return JsonResponse({'success': False, 'message': '请求方法错误'})


@login_required
def comment_like(request, comment_id):
    """点赞评论 - 优化版本"""
    from django.db import transaction
    from django.db.models import F
    import time

    max_retries = 5
    base_delay = 0.1

    for attempt in range(max_retries):
        try:
            with transaction.atomic():
                # 使用 select_for_update 锁定记录
                comment = ActivityComment.objects.select_for_update().get(id=comment_id)

                # 检查点赞状态
                like_exists = CommentLike.objects.filter(
                    user=request.user,
                    comment=comment
                ).exists()

                if like_exists:
                    # 取消点赞
                    deleted_count = CommentLike.objects.filter(
                        user=request.user,
                        comment=comment
                    ).delete()[0]

                    if deleted_count > 0:
                        # 确保点赞数不会变成负数
                        new_count = max(comment.likes_count - 1, 0)
                        ActivityComment.objects.filter(id=comment_id).update(
                            likes_count=new_count
                        )
                    action = 'unliked'
                else:
                    # 点赞 - 使用 get_or_create 避免重复创建
                    like, created = CommentLike.objects.get_or_create(
                        user=request.user,
                        comment=comment,
                        defaults={'user': request.user, 'comment': comment}
                    )

                    if created:
                        ActivityComment.objects.filter(id=comment_id).update(
                            likes_count=F('likes_count') + 1
                        )
                        action = 'liked'
                    else:
                        # 如果记录已存在，视为已点赞
                        action = 'liked'

                # 重新获取更新后的数据
                comment.refresh_from_db()

                return JsonResponse({
                    'success': True,
                    'action': action,
                    'likes_count': comment.likes_count,
                    'comment_id': comment_id
                })

        except Exception as e:
            if attempt < max_retries - 1:
                # 指数退避重试
                time.sleep(base_delay * (2 ** attempt))
                continue
            else:
                return JsonResponse({
                    'success': False,
                    'message': f'操作失败，请重试: {str(e)}'
                })

    return JsonResponse({
        'success': False,
        'message': '操作失败，请稍后重试'
    })


def activity_by_category(request, category_id):
    """按分类查看活动"""
    category = get_object_or_404(ActivityCategory, id=category_id)
    activities = Activity.objects.filter(
        category=category,
        status='approved'
    ).select_related('creator')
    
    context = {
        'category': category,
        'activities': activities,
    }
    return render(request, 'activities/activity_by_category.html', context)


def haversine(lon1, lat1, lon2, lat2):
    """计算两点间距离（公里）"""
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    r = 6371  # 地球半径（公里）
    return c * r


def nearby_activities(request):
    """附近活动"""
    lat = request.GET.get('lat')
    lng = request.GET.get('lng')
    radius = float(request.GET.get('radius', 5))  # 默认5公里
    
    if not lat or not lng:
        return JsonResponse({'success': False, 'message': '缺少位置信息'})
    
    lat = float(lat)
    lng = float(lng)
    
    # 获取所有有坐标的活动
    activities = Activity.objects.filter(
        status='approved',
        latitude__isnull=False,
        longitude__isnull=False
    ).select_related('creator', 'category')
    
    # 筛选距离内的活动
    nearby = []
    for activity in activities:
        distance = haversine(lng, lat, float(activity.longitude), float(activity.latitude))
        if distance <= radius:
            nearby.append({
                'id': activity.id,
                'title': activity.title,
                'location': activity.location,
                'distance': round(distance, 2),
                'latitude': float(activity.latitude),
                'longitude': float(activity.longitude),
            })
    
    # 按距离排序
    nearby.sort(key=lambda x: x['distance'])
    
    return JsonResponse({'success': True, 'activities': nearby})

def nearby_activities_page(request):
    """附近活动页面"""
    return render(request, 'activities/nearby_activities.html')


# import requests
# from django.http import JsonResponse
# from django.conf import settings
#
# def reverse_geocode(request):
#     lng = request.GET.get('lng')
#     lat = request.GET.get('lat')
#     key = settings.AMAP_WEB_SERVICE_KEY
#     url = f"https://restapi.amap.com/v3/geocode/regeo?location={lng},{lat}&key={key}&radius=100&extensions=all"
#     response = requests.get(url)
#     return JsonResponse(response.json())

import requests
import json
from django.http import JsonResponse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt


def reverse_geocode(request):
    """逆地理编码接口"""
    lng = request.GET.get('lng')
    lat = request.GET.get('lat')

    if not lng or not lat:
        return JsonResponse({
            'status': '0',
            'info': '缺少经纬度参数',
            'regeocode': None
        })

    try:
        key = settings.AMAP_WEB_SERVICE_KEY
        url = f"https://restapi.amap.com/v3/geocode/regeo?location={lng},{lat}&key={key}&radius=1000&extensions=base"

        print(f"调用高德逆地理编码API: {url}")  # 调试日志

        response = requests.get(url, timeout=10)
        response.raise_for_status()  # 如果响应状态码不是200，抛出异常

        result = response.json()
        print(f"高德API返回结果: {json.dumps(result, ensure_ascii=False, indent=2)}")  # 调试日志

        # 标准化返回格式
        if result.get('status') == '1':
            return JsonResponse({
                'status': '1',
                'info': 'OK',
                'regeocode': {
                    'formatted_address': result['regeocode']['formatted_address'],
                    'addressComponent': result['regeocode']['addressComponent'],
                    'pois': result['regeocode'].get('pois', [])
                }
            })
        else:
            return JsonResponse({
                'status': '0',
                'info': result.get('info', '逆地理编码失败'),
                'regeocode': None
            })

    except requests.exceptions.RequestException as e:
        print(f"逆地理编码网络错误: {e}")
        return JsonResponse({
            'status': '0',
            'info': f'网络请求失败: {str(e)}',
            'regeocode': None
        })
    except Exception as e:
        print(f"逆地理编码处理错误: {e}")
        return JsonResponse({
            'status': '0',
            'info': f'处理失败: {str(e)}',
            'regeocode': None
        })
